/**
 * 
 */
package com.cipe.cmrs.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cipe.cmrs.util.SpringContextProvider;

/**
 * @author Incepio
 * 
 */

public class WebappServletContextListener implements ServletContextListener { 

    /**
     * Logger for this class
     */
    private final Logger logger = LoggerFactory.getLogger(WebappServletContextListener.class);

    /**
     * tells the application that servlet context is ready to accept requests
     * 
     * @param event
     */
    public void contextInitialized(ServletContextEvent e) {
	ServletContext application;
	application = e.getServletContext();

	// set the spring context as a static member of SpringContextProvider so
	// that it is available
	// from all classes
	ApplicationContext ctx = WebApplicationContextUtils
		.getRequiredWebApplicationContext(application);
	SpringContextProvider.setContext(ctx);
	if (logger.isDebugEnabled()) {
	    logger.debug("Application context initialized... ");
	}
	
    }

    /**
     * 
     * @param event
     */
    public void contextDestroyed(ServletContextEvent event) {

		if (logger.isDebugEnabled()) {
		    logger.debug("Application context destroyed... ");
		}
		// if (logger.isDebugEnabled()) {
		logger.debug("Server is shutting down...");
		// }
		SpringContextProvider.setContext(null);
    }

}
